package com.tx.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaderValues.CLOSE;
import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_0;

/**
 * @author dengguoxing
 * @date 2019/10/31
 * description
 **/
public class CustomWebSocketHandle extends ChannelInboundHandlerAdapter {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private WebSocketServerHandshaker handshaker;

    /**
     * 路径
     */
    private String path;

    /**
     * 事件处理器
     */
    private final WebSocketListener webSocketListener;

    public CustomWebSocketHandle(WebSocketListener webSocketListener, String path) {
        this.webSocketListener = webSocketListener;
        this.path = path;
    }

    /**
     * 当前channel注册到EventLoop
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
    }

    /**
     * 当前channel从EventLoop取消注册
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
    }

    /**
     * 当前channel活跃的时候
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    /**
     * 当前channel不活跃的时候，也就是当前channel到了它生命周期末
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 处理关闭，onClosed
        try {
            webSocketListener.onClosed(ctx);
        } catch (Exception e) {
            logger.error("ws处理closed出错，错误信息：", e);
        }
        super.channelInactive(ctx);
    }

    /**
     * 当前channel从远端读取到数据
     * @param ctx
     * @param obj
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
        /**
         * HTTP接入，WebSocket第一次连接使用HTTP连接,用于握手
         */
        if (obj instanceof FullHttpRequest) {
            handleHttpRequest(ctx, (FullHttpRequest) obj);
        }

        /**
         * Websocket 接入
         */
        else if (obj instanceof WebSocketFrame) {
            handlerWebSocketFrame(ctx, (WebSocketFrame) obj);
        }


    }

    /**
     * channel read消费完读取的数据的时候被触发
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    /**
     * 用户事件触发的时候
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            if (idleStateEvent.state() == IdleState.WRITER_IDLE ||
                    idleStateEvent.state() == IdleState.READER_IDLE ||
                    idleStateEvent.state() == IdleState.ALL_IDLE) {

                // 处理读写没消息的事情, onHeartBroken
                try {
                    webSocketListener.onHeartBroken(ctx);
                } catch (Exception e) {
                    logger.error("ws处理onHeartBroken出错，错误信息：", e);
                }
            }
        }

        super.userEventTriggered(ctx, evt);
    }

    /**
     * channel的写状态变化的时候触发
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        super.channelWritabilityChanged(ctx);
    }

    /**
     * 处理异常
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.info("exception caught");

        cause.printStackTrace();
        // 处理错误，onFailure
        try {
            webSocketListener.onFailure(ctx, cause);
        } catch (Exception e) {
            logger.error("ws处理exception出错，错误信息：", e);
        }
        ctx.close();
    }


    private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
        try {
            // 如果HTTP解码失败，返回HHTP异常
            if (!req.decoderResult().isSuccess()
                    || !"websocket".equals(req.headers().get("Upgrade")) || !path.equalsIgnoreCase(req.uri())) {
                sendHttpResponse(ctx, req, new DefaultFullHttpResponse(
                        HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
                return;
            }

            // 构造握手响应返回，本机测试
            //注意，这条地址别被误导了，其实这里填写什么都无所谓，WS协议消息的接收不受这里控制
            WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                    getWebSocketLocation(req), null, false);
            handshaker = wsFactory.newHandshaker(req);
            if (handshaker == null) {
                WebSocketServerHandshakerFactory
                        .sendUnsupportedVersionResponse(ctx.channel());
            } else {
                handshaker.handshake(ctx.channel(), req);
            }

            // 链接成功, onOpen
            try {
                webSocketListener.onOpen(ctx, req);
            } catch (Exception e) {
                logger.error("ws处理open出错，错误信息：", e);
            }

            ReferenceCountUtil.retain(req);
        } catch (Exception e) {
            logger.error("链接ws失败，错误信息：", e);
        } finally {
            ReferenceCountUtil.release(req);
        }
    }


    private void handlerWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
        try {
            /**
             * 判断是否关闭链路的指令
             */
            if (frame instanceof CloseWebSocketFrame) {
                handshaker.close(ctx.channel(),
                        (CloseWebSocketFrame) frame.retain());
                return;
            }

            /**
             * 判断是否ping消息
             */
            if (frame instanceof PingWebSocketFrame) {
                ctx.channel().write(
                        new PongWebSocketFrame(frame.content().retain()));
                return;
            }

            /**
             * 本例程仅支持文本消息，不支持二进制消息
             */
            if (frame instanceof BinaryWebSocketFrame) {
                throw new UnsupportedOperationException(String.format(
                        "%s frame types not supported", frame.getClass().getName()));
            }

            /**
             * 文本消息，主要处理这个
             */
            if (frame instanceof TextWebSocketFrame) {
                // 处理消息。onMessage
                String msg = ((TextWebSocketFrame) frame).text();
                try {
                    webSocketListener.onMessage(ctx, msg);
                } catch (Exception e) {
                    logger.error("ws处理message出错，错误信息：", e);
                }
            }

            ReferenceCountUtil.retain(frame);

        } catch (UnsupportedOperationException e) {
            logger.error("ws处理收到消息出错，错误信息：", e);
        } finally {
            ReferenceCountUtil.release(frame);
        }
    }


    private static void sendHttpResponse(ChannelHandlerContext ctx,
                                         FullHttpRequest req, DefaultFullHttpResponse res) {
        // 返回应答给客户端
        if (res.status().code() != 200) {
            ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(),
                    CharsetUtil.UTF_8);
            res.content().writeBytes(buf);
            buf.release();
        }

        // 如果是非Keep-Alive，关闭连接
        if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) {
            // Tell the client we're going to close the connection.
            res.headers().set(CONNECTION, CLOSE);
            ctx.writeAndFlush(res).addListener(ChannelFutureListener.CLOSE);
        } else {
            if (req.protocolVersion().equals(HTTP_1_0)) {
                res.headers().set(CONNECTION, KEEP_ALIVE);
            }
            ctx.writeAndFlush(res);
        }
    }

    private String getWebSocketLocation(FullHttpRequest req) {
        String location = req.headers().get(HttpHeaderNames.HOST) + path;
        return "ws://" + location;
    }
}
